package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.constants.GoodsTypeConstant;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.BankTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleManTable;
import com.gdk.ksoft.data.entry.tables.SaleStatisticsTable;
import com.gdk.ksoft.data.entry.tables.SaleTable;
import com.gdk.ksoft.data.entry.tables.ShoppingCartGoodsTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.ui.works.models.FworkGoodsOrderModel;
import com.gdk.ksoft.ui.works.models.FworkOrderInfoModel;
import com.gdk.ksoft.assembly.dialog.BluetoothPrinterDialog;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.gdk.ksoft.assembly.utils.extensions.CanvasUtils;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.DbModelSelector;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zkc.helper.printer.PrinterClass;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 订单结算页面
 */
public class OrderStatisticsActivity extends Activity {

    @ViewInject(R.id.porderStatistics_txtIcon) private TextView txtIcon;//客户头像
    @ViewInject(R.id.porderStatistics_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.porderStatistics_txtCustomerAddress)private TextView txtCustomerAddress;//客户地址
    @ViewInject(R.id.porderStatistics_txtStatisticsMoney)private TextView txtStatisticsMoney;//结算金额
    @ViewInject(R.id.porderStatistics_txtContactor)private TextView txtContactor;//联系人信息
    @ViewInject(R.id.porderStatistics_txtContacts)private TextView txtDelieverGoodsInfo;//收货人信息
    @ViewInject(R.id.porderStatistics_txtDistace)private TextView txtDistance;//距离信息
    @ViewInject(R.id.porderStatistics_etBankMoney)private EditText etBankMoney;//银行金额
    @ViewInject(R.id.porderStatistics_txtBankSelector)private TextView txtBank;//银行金额
    @ViewInject(R.id.porderStatistics_etCash)private EditText etCash;//现金金额
    @ViewInject(R.id.porderStatistics_etMaling)private EditText etMaling;//抹零金额
    @ViewInject(R.id.porderStatistics_etDebt)private EditText etDebt;//欠款金额
    @ViewInject(R.id.porderStatistics_etDebtDays)private EditText etDebtDays;//欠款天数
    @ViewInject(R.id.porderStatistics_etNoteInfomation)private EditText etNoteInfomation;//备注信息

    private int netCustomerId = 0,netAddressId = 0;//客户网络ID,客户送货地址网络ID
    private int pieceNum = 0,singleNum = 0,kindsNum = 0;//商品件数，散数，种类数
    private String goodsCount = "";//商品数量
    private double totalMoney = 0;//总金额数
    private String[] bankNames = null;//银行账户集合
    private int[] bankIds = null;//银行账户ID集合
    private int selectorIndex = 0;//索引选择器
    private String orderNoForSale = "",orderNoForReturn = "";//销售单号,退货单号
    private List<ShoppingCartGoodsTable> saleGoodslist = null;//销售单商品集合
    private List<ShoppingCartGoodsTable> returnGoodslist = null;//退货单商品集合
//    private List<FworkGoodsOrderModel> saleOrderPrintlist = null;//销售单打印列表
//    private List<FworkGoodsOrderModel> returnOrderPrintlist = null;//退单打印列表
//    private HashMap<String,Object> saleOrderTotalInfo = null;//销售单统计信息
//    private HashMap<String,Object> returnOrderTotalInfo = null;//退单统计信息
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_statistics);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        Intent intent = getIntent();
        if(intent!=null) {//获取上个页面传过来的数据
            netCustomerId = intent.getIntExtra("netCustomerId", 0);//获取客户网络ID
            netAddressId = intent.getIntExtra("netAddressId", 0);//获取送货地址网络ID
            pieceNum = intent.getIntExtra("goodsPieceNum", 0);//获取商品件数
            singleNum = intent.getIntExtra("goodsSingleNum", 0);//获取商品散数
            kindsNum = intent.getIntExtra("goodsKindsNum", 0);//获取商品种类数
            totalMoney = intent.getDoubleExtra("goodsTotalMoney", 0);//获取商品总金额
            goodsCount = intent.getStringExtra("goodsCount");//获取商品数量
        }
        initActivity();//初始化参数
        initUIComponents();//初始化页面控件
    }

    @OnClick(value={R.id.porderStatistics_txtDebtStatistics,R.id.porderStatistics_txtPrint,
            R.id.porderStatistics_txtBankSelector})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.porderStatistics_txtDebtStatistics://结算
                if(bankNames == null || bankNames.length<=0){//检查银行账户的存在性
                    Toast.makeText(this,"后台未维护资金帐户，不能完成收款操作!",Toast.LENGTH_SHORT).show();
                    return;
                }
                double[] values = changeArguments();
                if(!FormatUtils.exactNumber(values[0]+values[1]+values[2]+values[3],"0.00")
                        .equals(FormatUtils.exactNumber(totalMoney,"0.00"))){
                    Toast.makeText(this,"结算错误，原因：结算金额值=抹零金额+现金+欠款+银行金额",Toast.LENGTH_SHORT).show();
                    return;
                }
                executeAddGoodsOrderTask(this,dbUtils);//执行添加商品的任务
                break;
            case R.id.porderStatistics_txtPrint://订单结算打印
                if(MainActivity.pl == null || MainActivity.pl.getState()!= PrinterClass.STATE_CONNECTED){
                    new BluetoothPrinterDialog(this,new BluetoothPrinterDialog.OnBluetoothConnectedListener() {
                        @Override
                        public void onBluetoothConnected(boolean isSuccessful) {
                            if(isSuccessful)
                                showPrintDialog();//显示打印窗口或直接打印提示
                            else
                                Toast.makeText(OrderStatisticsActivity.this,"当前未连接到打印机!",Toast.LENGTH_SHORT).show();
                        }
                    }).show();
                }else{
                    showPrintDialog();//显示打印窗口或直接打印提示
                }
                break;
            case R.id.porderStatistics_txtBankSelector://银行选择
                if(bankNames!=null && bankIds!=null) {
                    new AlertDialog.Builder(OrderStatisticsActivity.this).setItems(bankNames, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            txtBank.setText(bankNames[which]);
                            selectorIndex = which;
                        }
                    }).show();
                }else{
                    Toast.makeText(OrderStatisticsActivity.this,"没有银行账户数据可选择!",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化Activity页面控件
     */
    public void initUIComponents(){
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                double[] values= changeArguments();//获取系统改变的参数值
                String result = FormatUtils.exactNumber(totalMoney-(values[0]+values[2]+values[3]),"0.00");
                etCash.setText(result);//计算当前现金数
            }
        };
        etMaling.addTextChangedListener(textWatcher);
        //etCash.addTextChangedListener(textWatcher);
        etBankMoney.addTextChangedListener(textWatcher);
        etDebt.addTextChangedListener(textWatcher);
    }

    /**
     * 初始化页面
     */
    public void initActivity(){
        new AsyncTask<Void,Void,Void>(){
            private CustomerTable ct = null;
            private CustomerTypeTable ctt = null;
            private DeliverGoodsTable dt = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(OrderStatisticsActivity.this,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    ct = dbUtils.findFirst(Selector.from(CustomerTable.class).where("id","=",netCustomerId));
                    dt = dbUtils.findFirst(Selector.from(DeliverGoodsTable.class).where("id","=",netAddressId));
                    if(dt!=null) ctt = dbUtils.findFirst(Selector.from(CustomerTypeTable.class).where("id","=",dt.khlx));
                    List<BankTable> banklst = dbUtils.findAll(BankTable.class);
                    if(banklst!=null && banklst.size() > 0) {
                        bankNames = new String[banklst.size()];
                        bankIds = new int[banklst.size()];
                        for (int i = 0; i < banklst.size(); i++) {
                            BankTable item = banklst.get(i);
                            bankNames[i] = item.mc;
                            bankIds[i] = item.id;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null) dialog.dismiss();
                if(ct!=null && dt!=null && ctt!=null){
                    txtIcon.setText(ctt.dttb);
                    txtCustomerName.setText(ct.mc);
                    txtCustomerAddress.setText("地址："+dt.shdz);
                    txtContactor.setText(ct.lxr+" "+ct.dh);
                    txtDelieverGoodsInfo.setText(dt.shr+" "+dt.shdh);
                    txtStatisticsMoney.setText("结算金额："+ FormatUtils.exactNumber(totalMoney,"0.00")+"元");
                    etCash.setText(FormatUtils.exactNumber(totalMoney,"0.00"));
                    if(bankNames != null) txtBank.setText(bankNames[0]);
                    else  txtBank.setEnabled(false);
                    if(SystemData.currentLocation!=null && !TextUtils.isEmpty(dt.jwd.toString())){//计算距离信息
                        String[] latlngs = dt.jwd.split(",");
                        txtDistance.setText(FormatUtils.exactDistance(new LatLng(SystemData.currentLocation.getLatitude(),
                                SystemData.currentLocation.getLongitude()),new LatLng(Double.parseDouble(latlngs[0]),
                                Double.parseDouble(latlngs[1]))));
                    }
                }else{
                    Toast.makeText(OrderStatisticsActivity.this,"页面初始化失败!",Toast.LENGTH_SHORT).show();
                    OrderStatisticsActivity.this.finish();
                }
            }
        }.execute();
    }

    /**
     * 显示打印提示框（选择打印单据一联或者二联）
     */
    public void showPrintTipDialog(){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("请选择你要打印的单据的联数？","一联","二联");
        msgBox.setCanceledOnTouchOutside(false);
        msgBox.setCancelable(false);
        msgBox.setCloseVisiable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                goBackToMainPage();//关闭当前操作页面
            }
        });
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch(v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        printStatisticsOrder(dbUtils,1);//打印一联单据
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        printStatisticsOrder(dbUtils,2);//打印二联单据
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 打印结算清单
     */
    public void printStatisticsOrder(final DbUtils dbUtils,final int printCount){
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(OrderStatisticsActivity.this,"","正在打印...");

            }
            @Override
            protected Void doInBackground(Void... params) {
                int count = printCount;
                while(count>0){
                    try{
                        printOrderList(dbUtils,true);
                    }catch (Exception e){
                        e.printStackTrace();
                        errorMessage = e.getMessage();
                        return null;
                    }
                    try{
                        printOrderList(dbUtils,false);
                    }catch (Exception e){
                        errorMessage = e.getMessage();
                        e.printStackTrace();
                        return null;
                    }
                    count--;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                Toast.makeText(OrderStatisticsActivity.this,errorMessage!=null?"打印失败！原因："+errorMessage:"打印成功!",
                        Toast.LENGTH_SHORT).show();
//                if(errorMessage == null){//打印成功，无错误提示，此时关闭窗口
//                    goBackToMainPage();//返回主页
//                }
            }
        }.execute();
    }

    /**
     * 打印单子
     * @param isNormalOrder true - 订单   false - 退单
     * @throws Exception
     */
    public void printOrderList(final DbUtils dbUtils,final boolean isNormalOrder)throws Exception{
        if(isNormalOrder) orderNoForSale = requestOrderNo(isNormalOrder);//获取销售单号
        else orderNoForReturn = requestOrderNo(isNormalOrder);//获取销售退单号
        List<FworkGoodsOrderModel> orderModelList = null;//isNormalOrder?saleOrderPrintlist:returnOrderPrintlist;
        HashMap<String,Object> totalInfo = null;//isNormalOrder?saleOrderTotalInfo:returnOrderTotalInfo;
        if(isNormalOrder) {//销售单数据
            orderModelList = FworkDbHelper.findAllOrderPrintInfo(dbUtils, netCustomerId, netAddressId, 1);
            totalInfo = FworkDbHelper.getOrderTotalInfo(dbUtils, netAddressId, netCustomerId, 1);
        }
        if(!isNormalOrder) {//退货单数据
            orderModelList = FworkDbHelper.findAllOrderPrintInfo(dbUtils, netCustomerId, netAddressId, 0);
            totalInfo = FworkDbHelper.getOrderTotalInfo(dbUtils, netAddressId, netCustomerId, 0);
        }
        if(orderModelList == null || orderModelList.size()<=0) return;//不满足打印条件，不打印
        DbModel dbSaleMan = dbUtils.findDbModelFirst(DbModelSelector.from(SaleManTable.class).select("gsmc", "RealName"));
        DbModel dbCustomer = dbUtils.findDbModelFirst(DbModelSelector.from(CustomerTable.class).where("id", "=", netCustomerId).select("mc"));
        DbModel dbAddress = dbUtils.findDbModelFirst(DbModelSelector.from(DeliverGoodsTable.class).where("id", "=", netAddressId).select("shdz"));
        String companyName = dbSaleMan.getString("gsmc");
        final int WIDTH = 840,MARGIN = 5;//纸张宽度和纸张边距
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(34f);
        //绘制购货声明
        List<String> strlist = CanvasUtils.breakText(paint,SystemData.SaleDeclare,WIDTH);
        Bitmap bitmap = Bitmap.createBitmap(WIDTH, 700 + 40*(strlist==null?0:strlist.size())
                + 150 * orderModelList.size(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        float currentHeight = 0;//纸张当前高度
        paint.reset();
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);//设置文字居中
        paint.setTextSize(45f);
        currentHeight = CanvasUtils.drawText(canvas, paint, companyName + (isNormalOrder ? "销货清单" : "退货清单"), WIDTH / 2, currentHeight, -1);
        currentHeight = CanvasUtils.drawLine(canvas, paint, 5, currentHeight, WIDTH - 10, 4);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setTextSize(38f);
        currentHeight = CanvasUtils.drawText(canvas,paint,"客户："+dbCustomer.getString("mc"),MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"地址："+dbAddress.getString("shdz"),MARGIN,currentHeight,-1);
        String orderNo = isNormalOrder?orderNoForSale:orderNoForReturn;//获取单号
        currentHeight = CanvasUtils.drawText(canvas,paint,"单号："+orderNo,MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        final String[] columns = {"规格","发价","数量","金额"};
        for(int i=0;i<columns.length;i++){
            float py = CanvasUtils.drawText(canvas,paint,columns[i],MARGIN + i*(WIDTH-10)/columns.length,currentHeight,-1);
            if(i == columns.length-1) currentHeight = py;
        }
        paint.setTextSize(35f);
        for(FworkGoodsOrderModel item : orderModelList){//绘制商品列
            String goodsTm = (item.goodsType == 0?"":"("+ GoodsTypeConstant.getGoodsType().get(item.goodsType)+")")
                    +item.goodsInfo.tm;
            currentHeight = CanvasUtils.drawText(canvas,paint,goodsTm+"  "+item.goodsInfo.mc,0,currentHeight,WIDTH);
            CanvasUtils.drawText(canvas,paint,item.goodsInfo.gg,0,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint, "￥"+FormatUtils.exactNumber(item.finalPrice/item.goodsModuleInfo.hsgx,"0.00"),WIDTH/4,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint,(item.pieceNum==0?"":item.pieceNum+item.goodsModuleInfo.jldwmc)+(item.singleNum==0?"":item.singleNum+item.goodsInfo.dw),WIDTH/2,currentHeight,WIDTH/4);
            currentHeight = CanvasUtils.drawText(canvas,paint,"￥"+FormatUtils.exactNumber(item.totalMoney,"0.00"),3*WIDTH/4,currentHeight,WIDTH/4);
            if(item.goodsInfo.bzq!=0) {//如果保质期存在则打印，否则不打印
                CanvasUtils.drawText(canvas,paint,"生产日期："+item.goodsInfo.csrq,0,currentHeight,WIDTH/2);
                currentHeight = CanvasUtils.drawText(canvas, paint, "保质期：" + String.valueOf(item.goodsInfo.bzq) + "天", WIDTH / 2, currentHeight, WIDTH / 2);
            }
            currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        }
        paint.setTextSize(38f);
        if(totalInfo!=null) {//获取商品统计信息
            CanvasUtils.drawText(canvas, paint, totalInfo.get("totalPieceNum")+"件"+totalInfo.get("totalSingleNum")+"散", 0, currentHeight, WIDTH / 3);
            CanvasUtils.drawText(canvas, paint, totalInfo.get("totalKinds")+"种", WIDTH / 3, currentHeight, WIDTH / 3);
            currentHeight = CanvasUtils.drawText(canvas, paint, "￥"+FormatUtils.exactNumber(totalInfo.get("totalMoney"),"0.00"), 2 * WIDTH / 3, currentHeight, WIDTH / 3);
        }
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        float malingStr = Float.valueOf(ControlUtils.getNumberStringFromTextView(etMaling));
        CanvasUtils.drawText(canvas,paint,"抹零：￥"+FormatUtils.exactNumber(malingStr,"0.00"),0,currentHeight,WIDTH/2);
        float cashStr = Float.valueOf(ControlUtils.getNumberStringFromTextView(etCash));
        currentHeight = CanvasUtils.drawText(canvas, paint, "现金：￥" + FormatUtils.exactNumber(cashStr,"0.00"), WIDTH / 2, currentHeight, WIDTH / 2);
        float debtStr = Float.valueOf(ControlUtils.getNumberStringFromTextView(etDebt));
        CanvasUtils.drawText(canvas,paint,"欠款：￥"+FormatUtils.exactNumber(debtStr,"0.00"),0,currentHeight,WIDTH/2);
        currentHeight = CanvasUtils.drawText(canvas, paint, "账期：" + (etDebtDays.getText().length()>0?etDebtDays.getText() + "天":""), WIDTH / 2, currentHeight, WIDTH / 2);
        float bankStr = Float.valueOf(ControlUtils.getNumberStringFromTextView(etBankMoney));
        CanvasUtils.drawText(canvas,paint,"银行：￥"+ FormatUtils.exactNumber(bankStr,"0.00"),0,currentHeight,WIDTH/2);
        currentHeight = CanvasUtils.drawText(canvas, paint, "账户：" + (txtBank.getText().length()>0?txtBank.getText():""), WIDTH / 2, currentHeight, WIDTH / 2);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        CanvasUtils.drawText(canvas,paint,"销货人："+dbSaleMan.getString("RealName"),0,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"打印时间："+FormatUtils.standardDatetime(new java.util.Date(),"yyyy/MM/dd HH:mm:ss"),
                WIDTH/3,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"购货检验人(签字):",0,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        if(strlist!=null && strlist.size()>0){//销售声明
            paint.setTextSize(34f);
            for(int i=0;i<strlist.size();i++){
                currentHeight = CanvasUtils.drawText(canvas,paint,strlist.get(i),0,currentHeight,WIDTH);
            }
        }
//        FileUtils.writeImageToFile(bitmap, Bitmap.CompressFormat.JPEG, 100, "/sdcard/1.jpg");
        MainActivity.pl.printImage(bitmap);
    }

    /**
     * 请求商品的订单号
     * @param isNormalOrder true - 订单   false - 退单
     * @return
     * @throws Exception
     */
    public String requestOrderNo(boolean isNormalOrder){
        try {
            if (!NetworkUtils.isNetAvailable(OrderStatisticsActivity.this))
                return null;//如果网络不可用
            String methodName = isNormalOrder ? "Cx_XsdDjh" : "Cx_XstDjh";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
            System.out.println("-----> 请求单据号数据数据是：" + messageBody);
            RequestParams params = new RequestParams();
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            String result = FileUtils.stream2string(new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                    .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params), "UTF-8");
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    System.out.println("------>单据号【"+resultModel.Data+"】");
                    return resultModel.Data;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("请求单据号失败："+e.getMessage());
        }
        return "NO" + (isNormalOrder ? "B" : "S") + System.currentTimeMillis();
    }

    /**
     * 执行添加商品订单的任务
     */
    public void executeAddGoodsOrderTask(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            private ProgressDialog dialog = null;
            private boolean isTranaction = false;//是否开启了数据库事务
            private AsyncTask task = null;//任务对象

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                TaskUtils.sendMessageToBackgroundService(context, false);
                task = this;//当前任务的对象
                dialog = ProgressDialog.show(context,"","正在提交数据...");
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        try{
                            task.cancel(true);
                            task = null;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Toast.makeText(context,"您取消了提交订单的任务!",Toast.LENGTH_SHORT).show();
                        TaskUtils.sendMessageToBackgroundService(context,true);
                    }
                });
            }

            @Override
            protected Void doInBackground(Void... params) {
                SQLiteDatabase database = dbUtils.getDatabase();
                try {
                    Selector selector1 = Selector.from(ShoppingCartGoodsTable.class)
                            .where("kh_id", "=", netCustomerId).and("shdz_id", "=", netAddressId)
                            .and("hsdwsl", ">", 0);
                    saleGoodslist = dbUtils.findAll(selector1);//获取销售单列表
                    Selector selector2 = Selector.from(ShoppingCartGoodsTable.class)
                            .where("kh_id", "=", netCustomerId).and("shdz_id", "=", netAddressId)
                            .and("hsdwsl", "<", 0);
                    returnGoodslist = dbUtils.findAll(selector2);//获取退货单列表
                    if(saleGoodslist!=null && saleGoodslist.size()>0){//获取销售单等数据信息
                        orderNoForSale = TextUtils.isEmpty(orderNoForSale)?requestOrderNo(true):orderNoForSale;
                        if(TextUtils.isEmpty(orderNoForSale)) throw new Exception("获取销售单单号失败，是否使用临时单号?");
//                        saleOrderPrintlist = FworkDbHelper.findAllOrderPrintInfo(dbUtils,netCustomerId, netAddressId, 1);
//                        saleOrderTotalInfo = FworkDbHelper.getOrderTotalInfo(dbUtils,netAddressId,netCustomerId,1);
                    }
                    if(returnGoodslist!=null && returnGoodslist.size()>0){//获取退货单等数据信息
                        orderNoForReturn = TextUtils.isEmpty(orderNoForReturn)?requestOrderNo(false):orderNoForReturn;
                        if(TextUtils.isEmpty(orderNoForReturn)) throw new Exception("获取销售退货单单号失败，是否使用临时单号?");
//                        returnOrderPrintlist = FworkDbHelper.findAllOrderPrintInfo(dbUtils,netCustomerId, netAddressId, 0);
//                        returnOrderTotalInfo = FworkDbHelper.getOrderTotalInfo(dbUtils,netAddressId,netCustomerId,0);
                    }
                    database.beginTransaction();//开启数据库事务处理
                    isTranaction = true;//执行了Transaction的
                    //取销售单数据,并保存至本地中
                    FworkOrderInfoModel orderInfo = saveSaleGoodsOrder(dbUtils, saleGoodslist,orderNoForSale);
                    if (orderInfo != null) {
                        saveSaleOrder(dbUtils, orderInfo);
                        saveOrderStatistics(dbUtils, orderInfo, changeArguments());
                    }
                    //取退货单数据，并保存至本地中
                    orderInfo = saveSaleGoodsOrder(dbUtils, returnGoodslist, orderNoForReturn);
                    if (orderInfo != null) {
                        saveSaleOrder(dbUtils, orderInfo);
                        saveOrderStatistics(dbUtils, orderInfo, changeArguments());
                    }
                    dbUtils.delete(ShoppingCartGoodsTable.class, WhereBuilder.b("kh_id", "=", netCustomerId)//清空购物车商品数据
                            .and("shdz_id", "=", netAddressId));//清空购物车数据
                    if(isTranaction){
                        database.setTransactionSuccessful();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    errorMessage = e.getMessage();
                }finally {//提交事务任务
                    if(isTranaction){
                        database.endTransaction();//执行了数据库事务，则关闭
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                TaskUtils.sendMessageToBackgroundService(context,true);
                if(errorMessage!=null){
                    Toast.makeText(context,errorMessage,Toast.LENGTH_SHORT).show();
                    showErrorDialog(errorMessage);//显示错误提示窗口
                }else{
                    Toast.makeText(context,"付款结算完成！",Toast.LENGTH_SHORT).show();
                    goBackToMainPage();//返回首页
                }
            }
        }.execute();
    }

    /**
     * 显示错误提示窗口
     */
    public void showErrorDialog(final String errMsg){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("获取销售单单号失败，是否使用临时单号? ","确定","取消");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch(v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        orderNoForReturn = "NOS"+System.currentTimeMillis();//S-SMALL[数量为负数的单]
                        orderNoForSale = "NOB"+System.currentTimeMillis();//B-BIG[数量为正数的单]
                        executeAddGoodsOrderTask(OrderStatisticsActivity.this,dbUtils);//执行添加商品订单的任务
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 显示打印窗口或直接打印提示
     */
    public void showPrintDialog(){
        if(MainActivity.pl != null && MainActivity.pl.getState() == PrinterClass.STATE_CONNECTED){
            showPrintTipDialog();//选择打印
        }else{
            BluetoothPrinterDialog dialog = new BluetoothPrinterDialog(this,new BluetoothPrinterDialog.OnBluetoothConnectedListener() {
                @Override
                public void onBluetoothConnected(boolean isSuccessful) {
                    if(isSuccessful)//连接成功，开始选择打印
                        showPrintTipDialog();
                    else
                        Toast.makeText(OrderStatisticsActivity.this,"未连接到打印机!",Toast.LENGTH_SHORT).show();
                }
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    /**
     * 填写订单结算信息
     * @param dbUtils
     */
    public void saveOrderStatistics(DbUtils dbUtils,FworkOrderInfoModel orderInfo,double[] arguments) throws Exception{
        SaleStatisticsTable sst = new SaleStatisticsTable();
        sst.jsrq = FormatUtils.standardDatetime(new Date(),"yyyy-MM-dd HH:mm:ss");
        sst.xsd_id = orderInfo.orderNo;//销售单号
        sst.djh = orderInfo.orderNo;//单据号
        sst.kh_id = netCustomerId;//客户ID
        sst.shdz_id = netAddressId;//收货地址ID
        sst.jslx = 0;//结算类型 = 0
        sst.jsje = arguments[0]+arguments[1]+arguments[2]+arguments[3];//结算金额
        sst.xjje = arguments[1];//现金金额
        sst.yhje = arguments[2];//银行金额
        sst.yhzh_id = bankIds[selectorIndex];//银行账户ID
        sst.yhzh = txtBank.getText().toString();//银行账户
        sst.qkje = arguments[3];//欠款金额
        sst.zqts = (int)arguments[4];//欠款天数
        sst.mlje = arguments[0];//抹零金额
        sst.bz = etNoteInfomation.getText().toString();//备注信息
        dbUtils.save(sst);
    }

    /**
     * 改变不合法的参数
     */
    public double[] changeArguments(){
        String malingVal = ControlUtils.getNumberStringFromTextView(etMaling);
        String cashVal = ControlUtils.getNumberStringFromTextView(etCash);
        String banVal = ControlUtils.getNumberStringFromTextView(etBankMoney);
        String debtVal = ControlUtils.getNumberStringFromTextView(etDebt);
        String debtDayVal = ControlUtils.getNumberStringFromTextView(etDebtDays);
        double[] rets = new double[5];
        rets[0] = Double.parseDouble(malingVal);//抹零值
        rets[1] = Double.parseDouble(cashVal);//现金值
        rets[2] = Double.parseDouble(banVal);//银行金额
        rets[3] = Double.parseDouble(debtVal);//欠款金额
        rets[4] = Double.parseDouble(debtDayVal);//欠款天数
        return rets;
    }


    /**
     * 保存一个销售单
     * @param dbUtils
     * @return
     */
    public void saveSaleOrder(DbUtils dbUtils,FworkOrderInfoModel orderInfo)throws Exception{
        if(orderInfo == null) return;
        SaleTable saleTable = new SaleTable();
        saleTable.ddlx = 0;//此处是销售单
        saleTable.djbz = 0;//0表示单机
        saleTable.djh = orderInfo.orderNo;
        saleTable.fhsj = FormatUtils.standardDatetime(new java.util.Date(),"yyyy-MM-dd HH:mm:ss");
        saleTable.js = orderInfo.pieceNum;
        saleTable.ss = orderInfo.singleNum;
        saleTable.jsfs = 0;//此处暂时为0
        saleTable.kh_id = netCustomerId;
        saleTable.shdz_id = netAddressId;
        saleTable.pssm = etNoteInfomation.getText().toString();
        saleTable.sfje = orderInfo.totalMoney;
        saleTable.zqts = 0;//暂时为0
        saleTable.xdsj = FormatUtils.standardDatetime(new java.util.Date(),"yyyy-MM-dd HH:mm:ss");
        dbUtils.save(saleTable);//保存订单数据
    }

    /**
     * 储存销售单商品数据并删除该客户购物车数据
     * @param dbUtils
     * @throws Exception
     */
    public FworkOrderInfoModel saveSaleGoodsOrder(DbUtils dbUtils,List<ShoppingCartGoodsTable> goodslst,String orderNo)throws Exception{
        if(goodslst == null || goodslst.size()<=0) return null;//此时没有数据可保存
        FworkOrderInfoModel orderInfo = new FworkOrderInfoModel();
        orderInfo.orderNo = orderNo;//获取商品单号
        for(ShoppingCartGoodsTable item : goodslst){
            orderInfo.totalMoney+=item.yfje;//统计金额
            orderInfo.singleNum += item.xsdwss;//统计销售单位散数
            orderInfo.pieceNum += item.xsdwsl;//统计销售单位数量
        }
        for(ShoppingCartGoodsTable item : goodslst){
            SaleGoodsTable goodsVal = new SaleGoodsTable();
            goodsVal.bz = item.bz;
            goodsVal.bzlsj = item.bzlsj;
            goodsVal.bzq = item.bzq;
            goodsVal.bzxsdwj = item.bzxsdwj;
            goodsVal.csrq = item.zdsj;
            goodsVal.gg = item.gg;
            goodsVal.hsdw = item.hsdw;
            goodsVal.hsdwsl = item.hsdwsl;
            goodsVal.hsgx = item.hsgx;
            goodsVal.kh_id = item.kh_id;
            goodsVal.khdz_id = item.shdz_id;
            goodsVal.lx = item.lx;
            goodsVal.mc = item.mc;
            goodsVal.sp_id = item.sp_id;
            goodsVal.tm = item.tm;
            goodsVal.xsd_id = orderInfo.orderNo;
            goodsVal.xsdw = item.xsdw;
            goodsVal.xsdwsl = item.xsdwsl;
            goodsVal.xsdwss = item.xsdwss;
            goodsVal.xsyj = item.xsyj;
            goodsVal.yfje = item.yfje;
            goodsVal.zdsj = item.zdsj;
            dbUtils.save(goodsVal);
            //更新商品销量信息
            dbUtils.execNonQuery("update shangpin set xl = xl + "+item.hsdwsl+" where id = "+item.sp_id+";");
        }
        return orderInfo;
    }

    /**
     * 返回主页面
     */
    public void goBackToMainPage(){
        startActivity(new Intent(OrderStatisticsActivity.this, MainActivity.class));
        OrderStatisticsActivity.this.finish();
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.porderStatistics_txtBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
